// mutation 必须是同步函数 https://next.vuex.vuejs.org/zh/guide/mutations.html

import { arrToObj, formatData } from "@/utils";
import axios from "axios";

const mutations = {
  fetchColumns(state, payload) {
    const { data } = state.columns;
    const { list, count, currentPage } = payload.data;

    state.columns = {
      data: { ...data, ...arrToObj(formatData(list)) },
      total: count,
      currentPage: currentPage * 1,
    };
  },
  fetchColumn(state, payload) {
    state.columns.data[payload.data.id] = payload.data;
  },
  setLoading(state, status) {
    state.loading = status;
  },
  // JWT:Header + Payload + Signature https://jwt.io/introduction
  login(state, payload) {
    const { token } = payload.data;
    state.token = token;
    localStorage.setItem("token", token);
    // https://www.npmjs.com/package/axios#global-axios-defaults
    axios.defaults.headers.common.Authorization = `Bearer ${token}`;
  },
  logout(state) {
    state.token = "";
    state.user = { isLogin: false };
    localStorage.remove("token");
    delete axios.defaults.headers.common.Authorization;
  },
  fetchCurrentUser(state, payload) {
    state.user = { isLogin: true, ...payload.data };
  },
  setError(state, payload) {
    state.error = payload;
  },
  createPost(state, newPost) {
    state.posts.data[newPost._id] = newPost;
  },
  fetchPost(state, { data }) {
    state.posts.data[data._id] = data;
  },
  deletePost(state, { data }) {
    delete state.posts.data[data._id];
  },
  updatePost(state, { data }) {
    state.posts.data[data._id] = data;
  },
  // fetchPosts() {},
};

export default mutations;
